package com.example.stars_project_android.personalCenter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.stars_project_android.R;
import com.example.stars_project_android.util.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 修改密码界面
 */
public class EditPsd extends AppCompatActivity {
    private EditText editOldPsd, editNewPsd, editRePsd;  //旧密码，新密码，确认密码
    private ImageView newEye, reEye,imgBack; //新密码眼睛，确认密码眼睛
    private boolean isHide = false;  //输入框密码是否是隐藏，默认为false
    private Button btnEdit;  //立即修改按钮
    private String oldPsd, newPsd, rePsd;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            try {
                //处理子线程发送的消息
                String result = (String) msg.obj;
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                Toast.makeText(EditPsd.this,msgCon,Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_psd);
        //绑定控件对象
        setView();
        //设置点击事件
        newEye.setOnClickListener(view->{
            isShowPassword(editNewPsd);
        });
        reEye.setOnClickListener(view->{
            isShowPassword(editRePsd);
        });
        btnEdit.setOnClickListener(view->{
            if (editNewPsd.getText().toString().equals(editRePsd.getText().toString())){
                //与后端连接
                getConn();
            }else {
                Toast.makeText(this,"两次输入的密码不一致",Toast.LENGTH_LONG).show();
            }
        });
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EditPsd.this,IdSafe.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 点击眼睛图标显示密码明文或密文
     */
    private void isShowPassword(EditText editText) {
        if(isHide == false) {
            //R.mipmap.password_show是表示显示密码的“眼睛”图标
            reEye.setImageResource(R.mipmap.password_show);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            editText.setTransformationMethod(method1);
            isHide = true;
        } else {
            //R.mipmap.password_miss是表示隐藏密码的“眼睛+斜杠”图标
            reEye.setImageResource(R.mipmap.password_miss);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            editText.setTransformationMethod(method2);
            isHide = false;
        }
        //重置光标位置
        int index = editText.getText().toString().length();
        editText.setSelection(index) ;
    }

    /**
     * 获取网络连接
     */
    private void getConn() {
        //post请求向后端传递页面上获取的手机号和密码。
        //将数据封装
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("phoneNumber", Constant.phone);
//            jsonObject.put("oldPsd",editOldPsd.getText().toString());
//            jsonObject.put("newPsd",editNewPsd.getText().toString());
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        MediaType type = MediaType.parse("application/json;charset=utf-8");
//        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());
//        Log.e("传递的数据",jsonObject.toString());
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/userInfo/psdChange?phoneNumber="+Constant.phone+"&oldPsd="+editOldPsd.getText().toString()+"&newPsd="+editNewPsd.getText().toString())
//                .post(requestBody)
                .build();
        Log.e("请求路径：","http://192.168.1.7:8080/userInfo/psdChange?phoneNumber="+Constant.phone+"&oldPsd="+editOldPsd.getText().toString()+"&newPsd="+editNewPsd.getText().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端的数据
                Log.e("okhttp","请求成功");
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取用户输入的数据
     */
    private void getData() {
        oldPsd = editOldPsd.getText().toString();
        newPsd = editNewPsd.getText().toString();
        rePsd = editRePsd.getText().toString();
    }

    /**
     * 绑定控件对象
     */
    private void setView() {
        editOldPsd = findViewById(R.id.edit_old_psd);
        editNewPsd = findViewById(R.id.edit_new_psd);
        editRePsd = findViewById(R.id.edit_re_psd);
        newEye = findViewById(R.id.new_eye);
        reEye = findViewById(R.id.re_eye);
        btnEdit = findViewById(R.id.btn_edit);
        imgBack = findViewById(R.id.img_back);
    }
}